﻿/*
 * @Author: 宋绍华
 * @Date: 2024-12-18 13:43:53
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-09 09:13:34
 * @FilePath: \sr_system_manager_ui\src\plugins\download.ts
 * @Description: 
 */
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/utils'

let downloadLoadingInstance;

export default {
  saveAs(url: Blob | string, name: string, opts?:any) {
    saveAs(url, name, opts);
  },
  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
  },
  // 下载附件，带loading效果
  downloadFileSync(url, fileName) {
    downloadLoadingInstance = ElLoading.service({ text: "正在下载中...，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    // 利用axios 下载文件流，然后js执行a标签下载，需要加loading效果
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, fileName)
      } else {
        // this.printErrMsg(res.data);
        this.saveAs(url, fileName)
      }
      downloadLoadingInstance.close();
    }).catch((r) => {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    })
  }
}

